from rest_framework import serializers

from questions.models import Questions,Label,Answer
from users.models import User


class LabelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = '__all__'


class QuestionAutorSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','username','mobile')





class QuestionSerializer(serializers.ModelSerializer):
    author_name = QuestionAutorSerializer()
    labels = LabelSerializer(many=True)
    class Meta:
        model = Questions
        fields = ('id','author_name','title','create_time','content','clicks','pageviews','labels')



class SubsListSerializer(serializers.ModelSerializer):
    user = QuestionAutorSerializer()
    class Meta:
        model = Answer
        fields = ('id','user','content',)


class AnswerListSerializer(serializers.ModelSerializer):
    user = QuestionAutorSerializer()
    parent = SubsListSerializer()

    class Meta:
        model = Answer
        fields = ('id','user','content','clicks','create_time','question','parent')


class AnswerCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = ('user','content','question','parent')


class SimilarityQusetionsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Questions
        fields = ('id','title','answer_count')


class LabelRetrieveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = ('id','name','content')


class NewObserver(serializers.ModelSerializer):
    """
    返回新闻最新评论者和时间的序列化器
    """
    user = QuestionAutorSerializer()

    class Meta:
        model = Answer
        fields = ('user', 'create_time')


class QuestionInfo(serializers.ModelSerializer):
    """
    返回最终的问题列表
    """
    author_name = QuestionAutorSerializer()
    labels = LabelSerializer(many=True)


    class Meta:
        model = Questions
        fields = ('id', 'title', 'create_time', 'clicks', 'pageviews', 'answer_count', 'author_name', 'labels')





class HotLabelSerializer(serializers.ModelSerializer):
    """
    返回标签
    """
    class Meta:
        model = Label
        fields = '__all__'


class CreateQuestions(serializers.ModelSerializer):
    """
    创建问答
    """
    class Meta:
        model = Questions
        fields = ('author_name', 'title', 'labels', 'content')

    # def validate_labels(self, value):
    #     label_name = re.split(",|;", value)
    #     label_list=[]
    #     for i in label_name:
    #         try:
    #             label = Label.objects.get(name=i)
    #         except Label.DoesNotExist:
    #             raise serializers.ValidationError('标签不存在')
    #
    #         except Exception as e:
    #             raise serializers.ValidationError('数据库查询错误%s'% e)
    #
    #         label_list.append(str(label.id))
    #
    #     return label_list


